var path= require('path')
	,config=require('../config')
	,users = require('./users')
	,vms = require('./vms')
	,vm = require('./vm')
	,images = require('./images')
	//,benchmark = require('./benchmark')
	,restify= require('restify')
	,log = require('bunyan').createLogger({
		name:'server',level:'info',serializers: restify.bunyan.serializers,
		streams: [
			{
				level: 'info',
				stream: process.stdout
				//,path: '/inclog/info.log'
			},{
				level: 'error',
				//stream: process.stdout,
				path: '/inclog/error.log'
			}
			]
	})
	,app=restify.createServer({name:'incloud',log:log})
app.use(restify.queryParser())
app.use(restify.bodyParser())
app.use(restify.CORS())
app.use(restify.fullResponse())
app.get('/', function (req, res, next){
  var data = require('fs').readFileSync(path.join(__dirname,'..','public', 'index.html'));
  res.status(200);
  res.header('Content-Type', 'text/html');
  res.end(data.toString());
})
app.get(/^.*\.(html|png|svg|css|js|ico)$/,restify.serveStatic({directory: path.join(__dirname,'..','public')}))
app.use(function(req, res,next){
	var ua = req.headers['user-agent'],detector=require('detector')
	if(req.headers.userid===undefined&&req.method=='GET'){
		res.header('Location','/#'+req.url)
        return res.send(302);
	}
	next()
})/*
router.route('/benchmark')
	.get(images.listImages,packages.list,benchmark.view)
	.post(benchmark.post)*/
app.get('/login',users.loginView)
app.post('/login',users.loginAction)
app.get('/vms',vms.view)
app.get('/vm/:uuid',vm.get)
app.get('/action/:uuid/:action',vm.action)
app.get('/jobs/:id',require('./jobs').get)
app.on('after', function (req, res, route, error){req.log.info({err: error,url: req.url,route: route,params: req.params})})
app.on('uncaughtException', function (req, res, route, error) {req.log.fatal({err: error,url: req.url,route: route,params: req.params});res.send(error)})
app.listen(config.port,config.host,function(){console.log('Server  on %s:%s',config.host,config.port)})
process.on('uncaughtException', function(e){log.fatal(e, 'Uncaught Exception')})